using System;
using System.Threading;
using UniRx;
using UnityEngine;

namespace TccSys.Runtime
{
    [Serializable]
    public class CancellableConnector : Connector
    {
        [SerializeReference, SubclassSelector] ITrigger _cancellation;

        CancellationTokenSource _cts;
        IDisposable _disposable;
        protected override CancellationToken _cancellationToken
        {
            get
            {
                if (_cts == null)
                {
                    _cts = new CancellationTokenSource();
                    _disposable = _cancellation.Subscribe(_ => _cts.Cancel());
                }

                return _cts.Token;
            }
        }

        public override void Disconnect()
        {
            base.Disconnect();
            _disposable?.Dispose();
            _cts.Dispose();
            _cts = null;
        }
    }
}